#include "gdn/Window.h"

#include <iostream>

#include "gdn/Utility.h"

namespace gdn
{
	Window::~Window()
	{
		if ( IsOpen() )
		{
			Close();
		}
	}

	void Window::Create( const Vector2i& theSize, unsigned int theBpp, const std::string& theTitle )
	{
		window.Create( sf::VideoMode( theSize.x, theSize.y, theBpp ), theTitle );
		title = theTitle;
		pos.x = -1;
		pos.y = -1;
	}

	void Window::Close()
	{
		window.Close();
	}

	bool Window::IsOpen() const
	{
		return window.IsOpened();
	}

	const InputManager& Window::GetInput() const
	{
		return input;
	}

	bool Window::GetEvent( Event& event )
	{
		sf::Event Event;
		while ( window.PollEvent( Event ) )
		{
			gdn::Event theEvent = ConvertToGdn( Event );
			//std::cout<< "1 " << theEvent.type << " " << theEvent.key << " ";
			events.push( theEvent );

			if ( theEvent.type == Event::KeyPressed )
			{
				input.keys[ theEvent.key ] = true;
			}
			else if ( theEvent.type == Event::KeyReleased )
			{
				input.keys[ theEvent.key ] = false;
			}
			else if ( theEvent.type == Event::MouseButtonPressed )
			{
				input.mouseButtons[ theEvent.mouseButton ] = true;
			}
			else if ( theEvent.type == Event::MouseButtonReleased )
			{
				input.mouseButtons[ theEvent.mouseButton ] = false;
			}
			else if ( theEvent.type == Event::MouseMoved )
			{
				input.mousePos.x = theEvent.x;
				input.mousePos.y = theEvent.y;
			}
		}

		if ( events.size() >= 1 )
		{
			event = PeekEvent();
			PopEvent();
			return true;
		}
		return false;
	}

	Event Window::PeekEvent() const
	{
		return events.front();
	}

	void Window::PopEvent() const
	{
		events.pop();
	}

	bool Window::HasEvent() const
	{
		return events.size();
	}

	void Window::Clear()
	{
		window.Clear( sf::Color::White );
	}

	void Window::Draw( const Sprite& draw )
	{
		window.Draw( draw.sprite );
	}

	void Window::Draw( const Text& draw )
	{
		window.Draw( draw.text );
	}

	void Window::Display()
	{
		window.Display();
	}

	/*
	Image Window::GetScreenshot() const
	{
		return Image().image = window.();
	}//*/

	std::string Window::GetWindowTitle() const
	{
		return title;
	}

	void Window::SetWindowTitle( const std::string& theTitle )
	{
		window.SetTitle( theTitle );
		title = theTitle;
	}

	Vector2i Window::GetWindowPosition() const
	{
		return ConvertToGdn< int >( pos );
	}

	void Window::SetWindowPosition( const Vector2i& newPos )
	{
		window.SetPosition( newPos.x, newPos.y );
		pos.x = newPos.x;
		pos.y = newPos.y;
	}
}
